from django.db import models
from django.contrib.auth.models import User
import json


class Restaurant(models.Model):
    name = models.CharField(max_length=255)
    address = models.TextField()

    def __str__(self):
        return self.name


# Create your models here.
class Menu(models.Model):
    name = models.CharField(max_length=255, null=False, blank=False)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE,default=1)

    def __str__(self):
        return self.name

    class Meta:
        pass


class Order(models.Model):
    STATUS = [
        ('1', '正在下单'),
        ('2', '已下单,待接单'),
        ('3', '已接单,待结单'),
        ('4', '结单'),
    ]
    orderid = models.CharField(max_length=10)
    goods = models.CharField(max_length=255, default='{}')
    status = models.CharField(max_length=1, choices=STATUS, default='1')
    created_time = models.DateTimeField(auto_now_add=True)

    def get_totalcount(self):
        # 第一步,根据goods 字符串,还原订单 菜品详情
        goods = json.loads(self.goods)  # [{1:2}]
        # for k,v in goods:
        mysum = 0
        for cai_id, cai_count in goods:
            mysum += cai_count * Menu.objects.get(id=cai_id).price
        return mysum


# 学生 外卖小哥 信息拓展表
class UserProfile(models.Model):
    JOBS = [('1', "学生"), ('2', '外卖小哥')]
    home_address = models.TextField(null=True, default='')
    phone = models.CharField(max_length=11)
    job = models.CharField(max_length=1, choices=JOBS)
    # user = models.ForeignKey(User, unique=True,on_delete=models.CASCADE)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
